﻿using System;
using System.Configuration;
using System.Web;
using System.IO;

namespace Shuba.Web.target_plan
{
    public partial class regional_plan_upload : basePage
    {
        string msg = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                string acl = GetUserAccess("TARGET_REGIONAL");
                if (!IsUserAdd(acl))
                {
                    msg = this.GetGlobalResourceObject("Messages", "NoPrivilege").ToString();
                    AlertAndRedirect(msg, ResolveUrl(ConfigurationManager.AppSettings["default_url"]));
                }

                LabelTitle.Text = GetPageTitle("TARGET_REGIONAL");
            }
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                Boolean fileOK = false;
                String path = Server.MapPath("~/uploads/");

                if (FileUpload1.HasFile)
                {
                    String fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
                    String[] allowedExtensions = { ".txt", ".csv" };

                    for (int i = 0; i < allowedExtensions.Length; i++)
                    {
                        if (fileExtension == allowedExtensions[i])
                        {
                            fileOK = true;
                        }
                    }
                }

                if (fileOK)
                {
                    status.Visible = true;

                    try
                    {
                        int SuccessCount = 0;
                        string ErrMessage = "";
                        string fName = path + Session["UserID"].ToString() + FileUpload1.FileName;
                        FileUpload1.PostedFile.SaveAs(fName);

                        var filestream = File.OpenText(fName);
                        string contents = filestream.ReadToEnd();
                        filestream.Close();

                        var MstStd = new Business.RegionalTarget();
                        Shuba.Business.Regional re = new Shuba.Business.Regional();
                        
                        char rowDelimiter = '\n';
                        char fldDelimiter = '\t';
                        var rows = contents.Split(rowDelimiter);

                        for (var i = 1; i < rows.Length - 1; i++)
                        {
                            var fields = rows[i].Split(fldDelimiter);
                            if (fields.Length > 1)
                            {
                                if (re.Get(fields[0].Trim()).RegionalID == null) ErrMessage += "<BR> Invalid Regional, Regional Does Not Exist at Column : 1, Line :" + i.ToString();
                                if (!IsValidEntryFormat(fields[1].Trim(), "N")) ErrMessage += "<BR> Invalid Target Year Value or Format at Column : 2, Line :" + i.ToString();

                                if (!IsValidEntryFormat(fields[2].Trim().Replace(",", ""), "M")) ErrMessage += "<BR> Invalid Target Amount Value or Format at Column : 3, Line :" + i.ToString();
                                if (!IsValidEntryFormat(fields[3].Trim(), "N")) ErrMessage += "<BR> Invalid Noa Value or Format at Column : 4, Line :" + i.ToString();
                                if (!IsValidEntryFormat(fields[2].Trim().Replace(",", ""), "M")) ErrMessage += "<BR> Invalid Target Amount Value or Format at Column : 5, Line :" + i.ToString();
                                if (!IsValidEntryFormat(fields[3].Trim(), "N")) ErrMessage += "<BR> Invalid Noa Value or Format at Column : 6, Line :" + i.ToString();

                                if (ErrMessage == "")
                                {
                                    if (MstStd.Save(new Model.RegionalTargetInfo
                                    {
                                        RegionalID = fields[0].Trim(),
                                        TargetYear = fields[1].Trim(),
                                        TargetAmount = Convert.ToInt64(fields[2].Trim()),
                                        Noa = Convert.ToInt32(fields[3].Trim()),
                                        TargetAmountReal = Convert.ToInt64(fields[4].Trim()),
                                        NoaReal = Convert.ToInt32(fields[5].Trim()),
                                        ActType = "UPLOAD",
                                        EntryBy = HttpContext.Current.User.Identity.Name,
                                        EntryDate = ProcessingDate(),
                                        UpdateBy = HttpContext.Current.User.Identity.Name,
                                        UpdateDate = ProcessingDate()
                                    }) > 0) SuccessCount++;
                                }
                            }
                        }

                        File.Delete(fName);
                        AddLog("UPLOAD", "UPLOAD REGIONAL PLAN");

                        if (ErrMessage == "")
                        {
                            FileUpLoadValidator.Visible = false;
                            msg = "File Successfully Uploaded\\n\\nSuccessfully Upload : " + SuccessCount + " Record(s)";
                            AlertAndRedirect(msg, "regional_plan_list.aspx");
                        }
                        else
                        {
                            status.Visible = true;
                            lblStatus.Text = "<b>Error Found:</b><br>" + ErrMessage + "<br><br>";
                            FileUpLoadValidator.Visible = false;
                        }
                    }
                    catch (Exception ex)
                    {
                        msg = this.GetGlobalResourceObject("Messages", "UploadFailAlert").ToString();
                        lblStatus.Text = msg + "\n" + ex.Message;
                    }
                }
                else
                {
                    msg = this.GetGlobalResourceObject("Messages", "UploadInvalidFileAlert").ToString();
                    lblStatus.Text = msg;
                }
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("regional_plan_list.aspx");
        }
    }
}
